<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Structure extends MY_Controller {

	//构造函数
	public function __construct()
	{
		parent::__construct();
		$this->load->model('dxdb_model','str','structure');
	}

	public function struct_list()
	{
		$tmpStructs = $this->str->all();
		$data['structs'] = $this->format_struct($tmpStructs);
		$this->load->view('structure/str_list',$data);
	}

	public function struct_add()
	{
		if(IS_POST)
		{
		    $data = array();//表单内容
		    $data = $this->get_struct_data();
		    $this->db->insert('structure',$data);
		    $this->success('structure/struct_list','添加成功');
		}
		else
		{
		    $tmp_id = $this->uri->segment(3);
		    $data['st_pid'] = is_numeric($tmp_id) ? $tmp_id : false;
		    $tmpStructs = $this->str->all();
			$data['structs'] = $this->format_struct($tmpStructs);
		    $this->load->view('structure/str_add',$data);
		}
	}

	//栏目编辑
	public function struct_edit()
	{
		$cid = $this->uri->segment(3);
		if(IS_POST)
		{
		    $data = array();//表单内容
		    $data = $this->get_struct_data();
		    $this->db->update('structure',$data,array('st_id'=>$cid));
		    $this->success('structure/struct_list','编辑成功');
		}
		else
		{
			$tmpStructs = $this->str->all();
			$data['structs'] = $this->format_struct($tmpStructs);
			$data['cates'] = $this->db->get_where('structure',array('st_id'=>$cid))->row_array();
			$this->load->view('structure/struct_edit',$data);
		}
	}

    public function struct_del()
    {
    	$id = intval($this->input->post('id'));
    	// 判断是否有子类
    	$child = $this->str->all(array('st_pid'=>$id));
    	if(! empty($child))
    	{
    		 $arr['status']  = 0;
    		 $arr['message']  = "发现有子类，请谨慎删除,删除子类后再删除";     
    	}
    	else
    	{
	    	$flag = $this->cat->dx_delete(array('st_id'=>$id));
	    	if($flag)
	    	{
	    	  $arr['status']  = 1;
	    	  $arr['message']  = "删除信息成功 :)";
	    	}
	    	else
	    	{
	    	   $arr['status']  = 0;
	    	  $arr['message']  = "操作失败 :(";         
	    	} 	
    	}
    	echo json_encode($arr);
    	exit();
    }

	private function get_struct_data()
	{
		return array(
			"st_pid" 	=> $this->input->post('st_pid'),
			'st_title'	=> $this->input->post('st_title'),
			'st_url'  	=> $this->input->post('st_url'),
			'st_sort'  	=> $this->input->post('st_sort')
	    );
	}



	private function format_struct($data,$st_pid=0,$level = 1)
	{
	  $arr = array();
	  foreach ($data as $v) 
	  { 
	    if($v['st_pid'] == $st_pid)
	    {
	      if($v['st_pid'] != 0)
	      {
	        $v['st_title']= $v['st_title'];
	        $v['html'] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level - 1);
	        $arr[] = $v;
	      }
	      else
	      {
	      	$v['html'] = '';
	        $arr[] = $v;
	      }
	      $arr = array_merge($arr,static::format_struct($data, $v['st_id'],$level + 1));
	    }

	  }
	  return $arr;
	}
}